<template>
  <div id="fill-owner-info" :class="{'pb-0': type === 'part'}">
    <form-tips :tips="tips" v-if="type === 'page'"></form-tips>

    <grey-header title="车主信息" v-if="type === 'part'"></grey-header>

    <ul :class="{'mb-1': type === 'page'}">
      <li class="public-form-li">
        <label class="short">车主类型</label>
        <label for="person">个人
          <input
            type="radio"
            name="person"
            id="person"
            value="1"
            :disabled="allDisabled"
            v-model="ownerType">
        </label>
        <label for="group">单位
          <input
            type="radio"
            name="group"
            id="group"
            value="2"
            :disabled="allDisabled"
            v-model="ownerType">
        </label>
      </li>
      <li class="public-form-li">
        <label
          for="ownerName"
          class="short"
          v-text="+ownerType === 1 ? '车主姓名' : '单位名称'"></label>
        <input
          key="机动车所有人"
          type="text"
          id="ownerName"
          placeholder="请输入机动车所有人"
          name="机动车所有人"
          v-model="ownerName"
          v-validate="+ownerType === 1 ? 'required|userName' : 'required'"
          :disabled="allDisabled">
        <span v-show="VeeErrors.has('机动车所有人')">{{ VeeErrors.first('机动车所有人') }}</span>
      </li>
      <li class="public-form-li">
        <label
          for="ownerIdNum"
          class="short"
          v-text="+ownerType === 1 ? '车主身份证' : '证件号码'"></label>
        <template v-if="+ownerType === 1">
          <input
            key="所有人证件"
            type="text"
            id="ownerIdNum"
            placeholder="请输入所有人证件号"
            name="所有人证件"
            v-model="dataOwnerIdNum"
            v-validate="'required|idNum'"
            :disabled="allDisabled">
          <span v-show="VeeErrors.has('所有人证件')">{{ VeeErrors.first('所有人证件') }}</span>
        </template>

        <template v-else-if="+ownerType !== 1">
          <input
            key="统一社会信用代码"
            type="text"
            id="departmentIdNum"
            placeholder="请输入统一社会信用代码"
            name="统一社会信用代码"
            v-model="dataOwnerIdNum"
            v-validate="'required'"
            :disabled="allDisabled">
          <span v-show="VeeErrors.has('统一社会信用代码')">{{ VeeErrors.first('统一社会信用代码') }}</span>
        </template>
      </li>
      <template v-if="+ownerType === 1">
        <li class="public-form-li">
          <label class="long">长期身份证</label>
          <label for="shortTerm">是
            <input
              type="radio"
              name="shortTerm"
              id="shortTerm"
              value="1"
              :disabled="allDisabled"
              v-model="term">
          </label>
          <label for="longTerm">否
            <input
              type="radio"
              name="longTerm"
              id="longTerm"
              value="2"
              :disabled="allDisabled"
              v-model="term">
          </label>
        </li>
        <li class="public-form-li li-click" v-if="term === '2'">
          <label for="ownerExpirationDate" class="long">身份证有效期</label>
          <input
            key="idEndDate"
            type="button"
            id="ownerExpirationDate"
            :value="idEndDate"
            @click="openDatetimePicker"
            :disabled="allDisabled">
          <button
            class="date-btn"
            @click="openDatetimePicker"
            :disabled="allDisabled"></button>
        </li>
      </template>
      <li class="public-form-li" v-if="gotLicenceOrNot">
        <label for="licence" class="short">车牌号</label>
        <input
          key="车牌号"
          type="text"
          id="licence"
          placeholder="请输入车牌号"
          minlength="7"
          maxlength="7"
          name="车牌号"
          v-model="licence"
          v-validate="'required'"
          :disabled="allDisabled">
        <span v-show="VeeErrors.has('车牌号')">{{ VeeErrors.first('车牌号') }}</span>
      </li>
      <li class="public-form-li li-click" v-if="gotLicenceOrNot">
        <label for="licenceType" class="short">号牌种类</label>
        <input
          key="licenceType"
          type="button"
          id="licenceType"
          :value="licenceType"
          @click="openLicenceTypePicker"
          :disabled="allDisabled">
        <button
          class="type-btn"
          @click="openLicenceTypePicker"
          :disabled="allDisabled"></button>
      </li>
      <li class="public-form-li">
        <label
          for="ownerAddress"
          class="short"
          v-text="+ownerType === 1 ? '车主地址' : '单位地址'"></label>
        <input
          key="所有人详细地址"
          type="text"
          id="ownerAddress"
          placeholder="请输入所有人详细地址"
          name="所有人详细地址"
          v-model="ownerAddress"
          v-validate="'required'"
          :disabled="allDisabled">
        <span v-show="VeeErrors.has('所有人详细地址')">{{ VeeErrors.first('所有人详细地址') }}</span>
      </li>
      <li class="public-form-li" v-if="+ownerType === 2">
        <label for="contact" class="long">单位联系人</label>
        <input
          key="单位联系人"
          type="text"
          id="contact"
          placeholder="请输入单位联系人"
          name="单位联系人"
          v-model="contact"
          v-validate="'required|userName'"
          :disabled="allDisabled">
        <span v-show="VeeErrors.has('单位联系人')">{{ VeeErrors.first('单位联系人') }}</span>
      </li>
      <li class="public-form-li">
        <label
          for="ownerTel"
          class="short"
          v-text="+ownerType === 1 ? '车主电话' : '手机号'"></label>
        <input
          key="手机号"
          type="text"
          id="ownerTel"
          placeholder="请输入手机号"
          name="手机号"
          v-model="ownerTel"
          v-validate="'required|tel'"
          :disabled="allDisabled">
        <span v-show="VeeErrors.has('手机号')">{{ VeeErrors.first('手机号') }}</span>
      </li>
      <li class="public-form-li" v-if="+ownerType === 2">
        <label class="long">联系人性别</label>
        <label for="male">男
          <input
            type="radio"
            name="male"
            id="male"
            value="1"
            :disabled="allDisabled"
            v-model="contactGender">
        </label>
        <label for="female">女
          <input
            type="radio"
            name="female"
            id="female"
            value="2"
            :disabled="allDisabled"
            v-model="contactGender">
        </label>
      </li>
    </ul>

    <datetime-picker
      type="date"
      :startDate="startDate"
      :endDate="endDate"
      v-model="date"
      @confirm="confirmDate"
      @cancel="pickPopupChange(false)"
      ref="datetimePicker">
    </datetime-picker>

    <popup
      v-model="licenceTypePickerShow"
      position="bottom"
      class="licenceTypePopup">
      <picker
        :slots="licenceTypes"
        value-key="name"
        @change="pickedLicenceTypeChange">
      </picker>
    </popup>

    <grey-header :title="+ownerType === 1 ? '车主身份证' : '单位营业执照'" v-if="type === 'part'"></grey-header>

    <article class="public-form-article" :class="{'pt-1': type === 'part', 'mt-0': type === 'part'}">
      <header v-if="type === 'page'" v-text="+ownerType === 1 ? '请上传身份证正反面' : '请上传营业执照正副本'"></header>
      <section>
        <div class="item">
          <h2 v-text="+ownerType === 1 ? '身份证正面' : '营业执照正本'"></h2>
          <div class="public-input-wrap" @click="$tool.clickIdDom('idFrontInput')">
            <input
              type="file"
              id="idFrontInput"
              name="idFrontInput"
              @change="uploadIdCard($event, 'idFrontImg', 'idFrontLoading')">
            <div v-if="!idFrontLoading" class="cross">
              <span class="upright"></span>
              <span class="across"></span>
            </div>
            <spinner
              v-else-if="idFrontLoading"
              class="spinner"
              type="snake"
              color="#0097ff"></spinner>
            <img
              v-if="idFrontImg"
              :src="idFrontImg"
              alt="">
          </div>
        </div>
        <div class="item">
          <h2 v-text="+ownerType === 1 ? '身份证背面' : '营业执照副本'"></h2>
          <div class="public-input-wrap" @click="$tool.clickIdDom('idBackInput')">
            <input
              type="file"
              id="idBackInput"
              name="idBackInput"
              @change="uploadIdCard($event, 'idBackImg', 'idBackLoading')">
            <div v-if="!idBackLoading" class="cross">
              <span class="upright"></span>
              <span class="across"></span>
            </div>
            <spinner
              v-else-if="idBackLoading"
              class="spinner"
              type="snake"
              color="#0097ff"></spinner>
            <img
              v-if="idBackImg"
              :src="idBackImg"
              alt="">
          </div>
        </div>
      </section>
      <p v-if="type === 'page'" v-text="+ownerType === 1 ? '温馨提示：手动填写时，身份证照片可在下单时再提交，但必须提交后才能下单' : '温馨提示：手动填写时，营业执照照片可在下单时再提交，但必须提交后才能下单'"></p>
      <p>*建议上传1.5m，格式为jpg的照片</p>
    </article>

    <footer class="public-footer-btn-box" v-if="type === 'page'">
      <button
        v-if="+ownerType === 1"
        @click="ocrParseToText"
        :disabled="allDisabled"
        class="couple-button">OCR自动识别</button>
      <button
        @click="submit"
        :disabled="submitDisabled"
        :class="{'couple-button': +ownerType === 1, 'single-button': +ownerType === 2}">提交</button>
    </footer>
  </div>
</template>

<script>
  import { DatetimePicker, Toast, Indicator, Popup, Picker, Spinner } from 'mint-ui';
  import FormTips from './form-tips.vue';
  import GreyHeader from './grey-header.vue';
  export default {
    name: "fill-owner-info",
    components: {
      DatetimePicker,
      FormTips,
      GreyHeader,
      Popup,
      Picker,
      Spinner
    },
    props: ['type', 'info', 'editable', 'gotLicence'],
    data() {
      return {
        tips: '注：可使用OCR系统，拍摄身份证照片，自动识别证件信息',
        ownerType: '1',
        ownerName: '',
        dataOwnerIdNum: '',
        licence: '' || this.$route.query.plate_num,
        licenceType: '',
        licenceTypeCode: '',
        licenceTypes: [
          {
            flex: 1,
            values: [
              {
                name: '请选号牌种类'
              }
            ],
            textAlign: 'center'
          }
        ],
        licenceTypePickerShow: false,
        ownerTel: '',
        ownerAddress: '',
        date: '',
        startDate: new Date(),
        endDate: new Date(new Date().getFullYear() + 20, 11, 31),
        formattedYear: '' || '请选择',
        formattedMonth: '' || '请选择',
        formattedDay: '' || '请选择',
        idFrontImg: '',
        idFrontLoading: false,
        idBackImg: '',
        idBackLoading: false,
        submitDisabled: false,
        allDisabled: false,
        gotLicenceOrNot: false,
        term: '2',
        contact: '',
        contactGender: '1'
      }
    },
    computed: {
      idEndDate: {
        get() {
          return this.formattedYear + '-' + this.formattedMonth + '-' + this.formattedDay;
        },
        set(newValue) {
          if (newValue === '长期') {
            this.term = '1';
            this.formattedYear = '0000';
            this.formattedMonth = '00';
            this.formattedDay = '00';
          } else {
            let strings = newValue.toString().split('-');
            this.formattedYear = strings[0];
            this.formattedMonth = strings[1];
            this.formattedDay = strings[2];
          }
        }
      },
      ownerIdNum: {
        get() {
          return this.dataOwnerIdNum.toUpperCase();
        },
        set(newValue) {
          this.dataOwnerIdNum = newValue;
        }
      }
    },
    methods: {
      pickPopupChange(newVal) {
        this.$tool.fixedTheBG(newVal, 'fill-owner-info');
      },
      openDatetimePicker() {
        this.$refs.datetimePicker.open();
        this.pickPopupChange(true);
        // tag （this.pickPopupChange(false)）
        setTimeout(() => {
          document.getElementsByClassName('v-modal')[0].onclick = function () {
            this.pickPopupChange(false);
          }.bind(this)
        })
      },
      openLicenceTypePicker() {
        this.licenceTypePickerShow = true;
      },
      pickedLicenceTypeChange(picker, values) {
        if (values[0]) {
          this.licenceType = values[0].name;
          this.licenceTypeCode = values[0].code;
        }
      },
      confirmDate(date) {
        this.formattedYear = this.$tool.formattedDate(date).year;
        this.formattedMonth = this.$tool.formattedDate(date).month;
        this.formattedDay = this.$tool.formattedDate(date).day;

        this.pickPopupChange(false);
      },
      uploadIdCard(event, img, loading) {
        this[loading] = true;
        let formData = new FormData();
        formData.append('file', event.target.files[0]);
        this.$http.axios({
          url: this.$http.imgURL,
          method: 'post',
          data: formData
        }).then((res) => {
          this[loading] = false;
          if (res.data.error === 0) {
            this[img] = res.data.data.img_url;

            this.$emit('updateIdCard', res.data.data.img_url, img);
          } else if (res.data.error === 1) {
            alert(res.data.msg);
          }
        }).catch((error) => {
          this[loading] = false;
          console.log(error);
        })
      },
      submit() {
        this.$validator.validateAll().then((result) => {

          // 验证通过

          if (result) {
            this.$http.post({
              api: this.$api.INSURANCE_OWNER_INFO,
              params: {
                car_owner_type: this.ownerType,

                name: this.ownerName,
                num: this.ownerIdNum,
                end_date: this.idEndDate === '请选择-请选择-请选择' ? '' : this.idEndDate,
                phone: this.ownerTel,
                address: this.ownerAddress,
                linkman: this.contact,
                sex: this.contactGender,
                id_card_face: this.idFrontImg,
                id_card_back: this.idBackImg,
                user_id: localStorage.getItem('id'),

                // add、continue 时 必传 (有行驶证)

                plate_num: this.licence,
                plate_num_type: this.licenceTypeCode,

                // 修改时 必传 (有行驶证)

                car_owner_id: this.$route.params.id
              },
              success: (res) => {
                this.$tool.whenToast(
                  () => {

                    // 提示并禁止重复提交、点击，不再恢复（组件即将销毁）

                    this.submitDisabled = true;
                    this.allDisabled = true;
                  },
                  {
                    message: '提交成功，请继续完善车辆信息',
                    className: 'public-long-toast',
                    duration: -1
                  },
                  () => {

                    // 跳转到车辆信息页

                    this.$router.push({
                      name: 'FillCarInfo',
                      params: {
                        type: this.$route.query.type,
                        id: res.data.data.car_owner_id
                      }
                    });
                  },2000
                );
              }
            });
          } else {

            this.$tool.whenToast(
              () => {

                // 禁止重复点击

                this.submitDisabled = true;
              },
              {
                message: '请完善车主信息',
                duration: -1,
                iconClass: 'public-toast-icon error'
              },
              () => {

                // 恢复点击

                this.submitDisabled = false;
              },2000
            );
          }
        })
      },
      ocrParseToText() {
        if (!this.idFrontImg || !this.idBackImg) {
          Toast('需要客户的身份证正反面')
        } else {

          // 提示

          Indicator.open({
            text: '分析中...',
            spinnerType: 'snake'
          });

          // 禁止其它点击

          this.allDisabled = true;
          this.submitDisabled = true;

          let frontFormData = new FormData();
          frontFormData.append('file', document.getElementById('idFrontInput').files[0]);
          let backFormData = new FormData();
          backFormData.append('file', document.getElementById('idBackInput').files[0]);

          this.$http
            .all([this.parseIdCard(1, frontFormData), this.parseIdCard(2, backFormData)])
            .then(this.$http.spread(function (front, back) {

              // 关闭提示

              Indicator.close();

              // 释放其他点击

              this.allDisabled = false;
              this.submitDisabled = false;

              if (front.data.error === 0 && back.data.error === 0) {
                Toast('识别成功');

                this.ocrFrontDataProcess(front);

                this.ocrBackDataProcess(back);

              } else if (front.data.error === 1) {
                Toast('身份证正面识别失败');
              } else if (back.data.error === 1) {
                Toast('身份证背面识别失败');
              }
            }.bind(this)));
        }
      },
      parseIdCard(type, data) {
        return this.$http.axios({
          url: this.$http.ocrURL + '&type=' + type,
          method: 'post',
          data: data
        })
      },
      ocrFrontDataProcess(front) {

        // 姓名

        this.ownerName = front.data.data.ocr_info.name;

        // 身份证号码

        this.ownerIdNum = front.data.data.ocr_info.num;

        // 地址

        this.ownerAddress = front.data.data.ocr_info.address;
      },
      ocrBackDataProcess(back) {
        let date = back.data.data.ocr_info.end_date;
        if (date === '长期') {
          this.idEndDate = date;
        } else {
          this.formattedYear = date.substr(0, 4);
          this.formattedMonth = date.substr(4, 2);
          this.formattedDay = date.substr(6, 2);
        }
      }
    },
    created() {

      // 判断是否有车牌

      if (this.$route.query.type === 'add' || this.$route.params.type === 'add' || this.$route.params.type === 'continue' || this.gotLicence) {
        this.gotLicenceOrNot = true;
      }

      // 判断是否可编辑

      if (this.editable) {
        this.allDisabled = false;
      } else if (!this.editable) {
        this.allDisabled = true;
      }

      // 赋值

      if (this.type === 'part') {
        this.ownerType = this.info.ownerType;

        this.ownerName = this.info.name;
        this.ownerIdNum = this.info.idNum;
        this.idEndDate = this.info.idEffectTime || '请选择-请选择-请选择';
        this.licence = this.info.licence;
        this.licenceTypeCode = this.info.licenceType;
        this.ownerTel = this.info.tel;
        this.ownerAddress = this.info.address;
        this.contact = this.info.contact;
        this.contactGender = this.info.contactGender;

        this.idFrontImg = this.info.idFront;
        this.idBackImg = this.info.idBack;
      }

      // 获取号牌种类

      if (this.licence) {
        this.$http.post({
          api: this.$api.INSURANCE_LICENCE_TYPE,
          success: (res) => {
            this.licenceTypes = res.data.data;

            let data = res.data.data;
            data.unshift({
              // 据此判断是否已选择号牌种类
              id: '',
              code: '',
              name: '请选择号牌种类'
            });
            this.licenceTypes[0].values = data;

            if (this.info) {
              for (let i = 0; i < data.length; i++) {
                if (data[i].code === this.info.licenceType) {
                  setTimeout(() => {
                    this.licenceType = data[i].name;
                    this.licenceTypeCode = data[i].code;
                  }, 1000);
                  break;
                }
              }
            }
          }
        });
      }
    },
    watch: {
      'licenceTypePickerShow': 'pickPopupChange',
      'term': function(val) {
        if (val === '1') {
          this.idEndDate = '长期';
        } else if (val === '2') {
          this.idEndDate = '请选择-请选择-请选择';
        }
      },
      'ownerType': function (val) {
        this.$emit('isOwnerPersonType', +val === 1);
      }
    }
  }
</script>

<style lang="scss">

  #fill-owner-info {

    width: $size-as-parent;
    padding-bottom: $public-footer-btn-box-height;
    z-index: $content-z-index;

    >ul {
      padding: $public-form-padding;
      box-shadow: $public-box-shadow;
      background: $white;
    }

    >.licenceTypePopup {
      width: $size-as-parent;
      padding: 1rem 0;
    }
  }
</style>
